package com.ican.action.user;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ican.common.BusinessException;
import com.ican.common.hibernate.Page;
import com.ican.domain.user.Resources;
import com.ican.domain.user.Role;
import com.ican.domain.user.User;
import com.ican.domain.user.UserResources;
import com.ican.domain.user.UserRole;
import com.ican.service.user.ResourcesService;
import com.ican.service.user.RoleService;
import com.ican.service.user.UserService;
import com.ican.util.ContextUtils;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
    private static final long serialVersionUID = -7555806386280429294L;
    private static final Logger logger = LoggerFactory.getLogger(UserAction.class);
    
    private UserService userService;
    private RoleService roleService;
    private ResourcesService resourcesService;
    
    private List<Resources> resourcesList;
    private List<Role> roleList;
    private User user;
    private Page<User> page = new Page<User>();
    private String userResJson;
    private String checkResIds;
    
    public String toAddUser(){
        return "add";
    }
    
    public String addUser(){
        if(user == null || StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())){
            ContextUtils.errorMsg2Session("用户名及密码不能为空！");
            return "add";
        }
        try{
            userService.addUser(user);
            user = null;
            ContextUtils.successMsg2Session(null);
            return list();
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
            return "add";
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
            return "add";
        }
    }
    
    public String list(){
        try{
            page = userService.findAllUser(page, user);
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "list";
    }
    
    public String modifyUserStatus(){
        try{
            userService.modifyUserStatus(user.getId(), user.getDataStatus());
            ContextUtils.successMsg2Session(null);
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return list();
    }
    
    public String toEditUser(){
        user = userService.getLoginUserFromSession();
        return "edit";
    }
    
    public String editUser(){
        try{
            userService.modifyUserNameAndPw(user);
            ContextUtils.successMsg2Session(null);
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "edit";
    }
    
    public String userResource(){
        try{
            //用户已经拥有的菜单
            resourcesList = resourcesService.findResourceByUserId(user.getId());
            List<Integer> rids = new ArrayList<Integer>();
            for(Resources r : resourcesList){
                rids.add(r.getId());
            }
            //所有菜单
            resourcesList = resourcesService.getAllResource(0);
            StringBuffer sb = new StringBuffer();
            if(resourcesList != null && resourcesList.size() > 0){
                Resources r = null;
                sb.append("[");
                for(int i = 0; i < resourcesList.size(); i++){
                    r = resourcesList.get(i);
                    sb.append("{id:" + r.getId().toString() + ",");
                    if(r.getPid() == null){
                        sb.append("pId:0,");
                    }else{
                        sb.append("pId:" + r.getPid().intValue() + ",");
                    }
                    sb.append("name:\"" + r.getName() + "\",");
                    if(rids.contains(r.getId())){
                        sb.append("checked:true}");
                    }else{
                        sb.append("checked:false}");
                    }
                    if(i < resourcesList.size() - 1){
                        sb.append(",");
                    }
                }
                sb.append("]");
            }
            userResJson = sb.toString();
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "resources";
    }

    public String modifyUserResource(){
        try{
            if(checkResIds != null && checkResIds.length() > 0){
                //用户已经拥有的菜单
                resourcesList = resourcesService.findResourceByUserId(user.getId());
                List<Integer> ridOld = new ArrayList<Integer>();
                for(Resources r : resourcesList){
                    ridOld.add(r.getId());
                }
                Integer id = null;
                for(String s : checkResIds.split(",")){
                    id = Integer.parseInt(s.trim());
                    if(id != 1){
                        if(ridOld.contains(id)){
                            userService.removeUserResources(new UserResources(user.getId(), id));
                        }else{
                            userService.addUserResources(new UserResources(user.getId(), id));
                        }
                    }
                }
            }
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return userResource();
    }

    public String userRole(){
        try{
            //用户已经拥有的角色
            roleList = roleService.findRoleByUserId(user.getId());
            List<Integer> rids = new ArrayList<Integer>();
            for(Role r : roleList){
                rids.add(r.getId());
            }
            //所有菜单
            roleList = roleService.findAllRole(0);
            StringBuffer sb = new StringBuffer();
            if(roleList != null && roleList.size() > 0){
                Role r = null;
                sb.append("[");
                for(int i = 0; i < roleList.size(); i++){
                    r = roleList.get(i);
                    sb.append("{id:" + r.getId().toString() + ",");
                    sb.append("pId:0,");
                    sb.append("name:\"" + r.getName() + "\",");
                    if(rids.contains(r.getId())){
                        sb.append("checked:true}");
                    }else{
                        sb.append("checked:false}");
                    }
                    if(i < roleList.size() - 1){
                        sb.append(",");
                    }
                }
                sb.append("]");
            }
            userResJson = sb.toString();
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "role";
    }

    public String modifyUserRole(){
        try{
            if(checkResIds != null && checkResIds.length() > 0){
                //用户已经拥有的角色
                roleList = roleService.findRoleByUserId(user.getId());
                List<Integer> ridOld = new ArrayList<Integer>();
                for(Role r : roleList){
                    ridOld.add(r.getId());
                }
                Integer id = null;
                for(String s : checkResIds.split(",")){
                    id = Integer.parseInt(s.trim());
                    if(ridOld.contains(id)){
                        roleService.removeUserRole(new UserRole(user.getId(), id));
                    }else{
                        roleService.addUserRole(new UserRole(user.getId(), id));
                    }
                }
            }
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return userRole();
    }
    
    @Resource
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @Resource
    public void setResourcesService(ResourcesService resourcesService) {
        this.resourcesService = resourcesService;
    }
    @Resource
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public List<Resources> getResourcesList() {
        return resourcesList;
    }
    public void setResourcesList(List<Resources> resourcesList) {
        this.resourcesList = resourcesList;
    }
    public String getUserResJson() {
        return userResJson;
    }
    public void setUserResJson(String userResJson) {
        this.userResJson = userResJson;
    }
    public String getCheckResIds() {
        return checkResIds;
    }
    public void setCheckResIds(String checkResIds) {
        this.checkResIds = checkResIds;
    }
    public Page<User> getPage() {
        return page;
    }
    public void setPage(Page<User> page) {
        this.page = page;
    }
    public List<Role> getRoleList() {
        return roleList;
    }
    public void setRoleList(List<Role> roleList) {
        this.roleList = roleList;
    }
}
